'use strict';
var URI = 'https://tianheng.xlxiot.com/wx';
var fetch = require('./fetch');
var Const = require('./const');
var wechat = require('./wechat');

/**
 * 天恒电池小程序项目API
 *
 * @param  {String} type   类型，例如：'coming_soon'
 * @param  {Objece} params 参数
 * @return {Promise}       包含抓取任务的Promise
 */
function fetchApi(type, params) {
	return fetch(URI, type, params);
}

/**
 * 获取列表类型的数据
 * @param  {String} type   类型，例如：'coming_soon'
 * @param  {Number} page   页码
 * @param  {Number} count  页条数
 * @param  {String} search 搜索关键词
 * @return {Promise}       包含抓取任务的Promise
 */
function find(type) {
	var page = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
	var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
	var search = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';

	var params = {pageNum: page, pageSize: count, ticket: getApp().data.token};
	return fetchApi(type, search ? Object.assign(params, {q: search}) : params).then(function (res) {
		return dataHandler(res);
	});
}

/**
 * 通用接口 API
 * @param  {String} path   类型，例如：'coming_soon'
 * @param  {Json}   params   页码
 * @return {Promise}       包含抓取任务的Promise
 */
function common(path, params) {
	return fetchApi(path, params).then(function (res) {
		console.log('url path is ' + path);
		// console.log(res);
		return dataHandler(res);
	});
}

/**
 * 获取单条类型的数据
 * @param  {String} path   地址
 * @param  {Number} id     id
 * @return {Promise}       包含抓取任务的Promise
 */
function findOne(path, id) {
	return fetchApi(path, {ticket: getApp().data.token, id: id}).then(function (res) {
		return dataHandler(res);
	});
}

/**
 * 登录检测
 * @return {Promise}      包含抓取任务的Promise
 */
function testLogin() {
	return fetchApi('member/detail', {ticket: getApp().data.token}).then(function (res) {
		return dataHandlerNoLogin(res);
	});
}

/**
 * 上传头像 API
 * @param  {Json}   params 参数
 * @return {Promise}       包含抓取任务的Promise
 */
function uploadAvatar(path, params) {
	console.log('member/reAvatar');
	return wechat.uploadFile(
		URI + '/member/reAvatar',
		'file',
		path,
		Object.assign({ticket: getApp().data.token}, params)
	).then(function (res) {
		if (res.statusCode == 200) {
			res.data = JSON.parse(res.data);
		}
		return dataHandler(res);
	}).catch(function (e) {
		console.log(e);
	});
}

/**
 * 接口数据处理
 * @param  {Json} response API返回
 * @return {Json}          可用数据
 */
function dataHandler(response) {
	var resultMessage = 'SYSTEM ERROR';

	if (response.statusCode == 200) {
		if (response.data.hasOwnProperty('code')) {
			var code = response.data.code;
			if (code == Const.SUCCESS.DEFAULT) {
				return response.data.data;
			} else if (code == Const.ERROR.NOT_LOGIN) {
				console.log('not login');
				wx.navigateTo({
					url: '/pages/user/login/login?type=' + Const.TOPTIPS.WARN + '&msg=' + Const.ERROR_MSG.NOT_LOGIN
				})
			} else if (code == Const.ERROR.LOGIN_REPEAT) {
				wx.navigateTo({
					url: '/pages/user/login/login?type=' + Const.TOPTIPS.WARN + '&msg=' + Const.ERROR_MSG.LOGIN_REPEAT
				})
			} else if (code == Const.ERROR.NO_PERMISSION) {
				resultMessage = Const.ERROR_MSG.NO_PERMISSION;
			} else if (code == Const.ERROR.NOT_FOUND) {
				console.log('not found')
			} else if (code == Const.ERROR.SYSTEM_ERROR) {
				console.log(Const.ERROR_MSG.SYSTEM_ERROR);
				resultMessage = Const.ERROR_MSG.SYSTEM_ERROR;
			} else if (code == Const.ERROR.DEFAULT) {
				resultMessage = response.data.message;
			} else {
				resultMessage = Const.ERROR_MSG.UNKNOW_ERROR;
			}
		}
	} else {
		wx.showToast({
			title: Const.ERROR_MSG.ERROR_NETWORK,
			duration: 2000
		});
		resultMessage = Const.ERROR_MSG.ERROR_NETWORK;
	}

	return {code: 0, message: resultMessage};
}

/**
 * 接口数据处理 无登录校验
 * @param  {Json} response API返回
 * @return {Json}          可用数据
 */
function dataHandlerNoLogin(response) {
	var resultMessage = 'SYSTEM ERROR';

	if (response.statusCode == 200) {
		if (response.data.hasOwnProperty('code')) {
			var code = response.data.code;
			if (code == Const.SUCCESS.DEFAULT) {
				return response.data.data;
			} else if (code == Const.ERROR.NOT_LOGIN) {
				return false;
			} else if (code == Const.ERROR.LOGIN_REPEAT) {
				return false;
			} else if (code == Const.ERROR.NO_PERMISSION) {
				resultMessage = Const.ERROR_MSG.NO_PERMISSION;
			} else if (code == Const.ERROR.NOT_FOUND) {
				console.log('not found')
			} else if (code == Const.ERROR.SYSTEM_ERROR) {
				resultMessage = Const.ERROR_MSG.SYSTEM_ERROR;
			} else if (code == Const.ERROR.DEFAULT) {
				resultMessage = response.data.message;
			} else {
				resultMessage = Const.ERROR_MSG.UNKNOW_ERROR;
			}
		}
	} else {
		wx.showToast({
			title: Const.ERROR_MSG.ERROR_NETWORK,
			duration: 2000
		});
		resultMessage = Const.ERROR_MSG.ERROR_NETWORK;
	}

	return {code: 0, message: resultMessage};
}

module.exports = {
	find: find,
	findOne: findOne,
	common: common,
	uploadAvatar: uploadAvatar,
	testLogin: testLogin
};
